package cn.boltzjf.sql4j.dao;

import java.util.HashMap;
import java.util.Map;

import cn.boltzjf.sql4j.Column.Type;

public class ValueConverter {
    
    public static final ValueConverter DEFAULT_INSTANCE = new ValueConverter();

    public static interface DbValueWriter {
        public Object convert(Object s, Type type);
    }
    
    public static interface DbValueReader {
        public Object convert(Object s, Type type);
    }
    
    private final Map<Type, DbValueWriter> writerRegistry = new HashMap<>();
    private final Map<Type, DbValueReader> readerRegistry = new HashMap<>();
    
    public void registerDbValueWriter(Type type, DbValueWriter writer) {
        writerRegistry.put(type, writer);
    }

    public void registerDbValueReader(Type type, DbValueReader reader) {
        readerRegistry.put(type, reader);
    }
    
    private DbValueWriter getDbValueWriter(Type type) {
        return writerRegistry.get(type);
    }
    
    private DbValueReader getDbValueReader(Type type) {
        return readerRegistry.get(type);
    }
    
    public Object toDb(Object s, Type type) {
        if (s == null) {
            return null;
        }
        if (type == null) {
            return s;
        }
        DbValueWriter c = getDbValueWriter(type);
        return c != null ? c.convert(s, type) : s;
    }
    
    public Object fromDb(Object s, Type type) {
        if (s == null) {
            return null;
        }
        if (type == null) {
            return s;
        }
        DbValueReader c = getDbValueReader(type);
        return c != null ? c.convert(s, type) : s;
    }

}
